package com.hxd.otc.widget;

import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.widget.TextView;

import com.hxd.otc.R;
import com.hxd.otc.utils.DataUtils;

/**
 * 项  目 :  OrderSupervisor
 * 包  名 :  com.hengxunda.ordersupervisor.widget
 * 类  名 :  MessageHandler
 * 作  者 :  胡庆岭
 * 时  间 :  2018/5/15 17:46
 * 描  述 :  ${TODO} 发送消息Handler
 */
public class MessageHandler {
    public static final int MESSAGE_WHAT = 100;
    private int mTime = 60;
    private TextView mTextView;

    private Handler mHandler;

    public MessageHandler(TextView textView) {
        this.mTextView = textView;
        initHandler();
    }


    public void postMessage(final @NonNull String phoneNumber, final OnClickHandlerMessage onClickHandlerMessage) {
        if (DataUtils.isPhoneNumber(phoneNumber)) {
            mTextView.setText(mTime + "s");
            if (mTextView.isClickable()) {
                mTextView.setClickable(false);
                mTextView.setBackgroundResource(R.drawable.shape_no_click_button);
            }
            if (onClickHandlerMessage != null) {
                onClickHandlerMessage.onMessage();
            }
            mHandler.sendEmptyMessageDelayed(MessageHandler.MESSAGE_WHAT, 1000);
        }
    }

    private void initHandler() {
        mHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                switch (msg.what) {
                    case MESSAGE_WHAT:
                        if (mTime > 0) {
                            mTime--;
                            if (mTextView.isClickable()) {
                                mTextView.setClickable(false);
                                mTextView.setBackgroundResource(R.drawable.shape_no_click_button);
                            }
                            mHandler.sendEmptyMessageDelayed(MessageHandler.MESSAGE_WHAT, 1000);
                            mTextView.setText(mTime + "s");
                        } else {
                            mTextView.setClickable(true);
                            mTextView.setBackgroundResource(R.drawable.selector_click_button);
                            mTextView.setText(R.string.get_phone_code);
                            mTime = 60;
                        }
                        break;
                }
                return true;
            }
        });
    }

    public interface OnClickHandlerMessage {
        void onMessage();
    }

    /**
     * 用完的时候一定要记得去销毁
     */
    public void destroy() {
        mHandler.removeMessages(MESSAGE_WHAT);
        mHandler = null;
    }
}
